const jwt = require('jsonwebtoken')
const {
    createUser,
    getUserListServe,
    getCurrentUserInfoServe,
    getUserById,
    updateUserServe,
    deleteUserServe,
    updateUserStatusServe
} = require('../serve/user.serve')
const {getRoleById} = require('../serve/role.serve')
const {getMenuServe} = require('../serve/menu.serve')
const {uniqueFunc, JWT_SECRET} = require('../utils')
const redis = require('../utils/redis')
const ResultData = require('../config/resultData')

class UserController {
    async register(ctx, next) {
        const {username, password, nickname} = ctx.request.body
        try {
            const res = await createUser(username, password, nickname)
            ctx.body = {
                status: 0,
                msg: '用户注册成功'
            }
        } catch (err) {
            console.log(err);
            ctx.body = {
                status: 1,
                msg: err.message
            }
        }
    }

    async login(ctx, next) {
        const {id, username} = ctx.userInfo;
        console.log(ctx.userInfo, '上面传下来的用户信息');
        try {
            console.log(id)
            // 1，现在redis查当前用户是否为登陆状态
            const isUserLogin = await redis.get(id);
            let token = ''
            let setRedisStatus = ''
            console.log(isUserLogin,'isUserLogin')
            if (isUserLogin && JSON.parse(isUserLogin).token) { //如果当前用户已经登录，说明在在数据里里面已经有token信息了，就不用重新生成token了
                token = JSON.parse(isUserLogin).token
                new ResultData(0,'用户登录成功2222',{token}).requestResult(ctx)
            } else {
                token = jwt.sign({id, username}, JWT_SECRET, {expiresIn: '1d'})
                setRedisStatus = await redis.set(id, JSON.stringify({token}))
                redis.expire(id, 60 * 60 * 24)
                console.log(setRedisStatus)
                if (setRedisStatus === 'OK') {
                    new ResultData(0,'用户登录成功',{token}).requestResult(ctx)
                }
            }
        } catch (e) {
            console.log(e);
            new ResultData(1,'用户登录失败').requestResult(ctx)
        }
    }

    async layout(ctx, next) {
        //1.获取到当前用户id
        let id = ctx.state.user.id
        try {
            //2.根据用户id查找redis是否有以此id为key值得对象
            const res = await redis.get(id)
            //3.如果找到该id存储得对象，并且有token
            if (res && JSON.parse(res).token) {
                //4.删除该id对象
                await redis.del(id)
                new ResultData(0,'退出登录成功').requestResult(ctx)
            } else {
                new ResultData(1,'查找不到该用户').requestResult(ctx)
            }
        } catch (e) {
            console.log(e);
            new ResultData(1,'退出登录失败').requestResult(ctx)
        }
    }

    async getUserList(ctx, next) {
        try {
            const res = await getUserListServe(ctx);
            res.data = res.data.map(user => {
                const roleName =
                    user.Roles && user.Roles.length > 0
                        ? user.Roles.map(role => {
                            returnc
                        }).join(',')
                        : ''
                return {
                    roleName,
                    ...user.dataValues
                }
            })
            ctx.body = {
                status: 0,
                data: {
                    total: res.total,
                    pageSize: Number(res.pageSize),
                    pageNum: Number(res.pageNum),
                    pageData: res.data
                },
                msg: '获取列表成功'
            }
            new ResultData(0,'退出登录失败').requestResult(ctx)
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message
            }
        }
    }

    async getCurrentUserInfo(ctx) {
        const {id: userId} = ctx.state.user;
        try {
            //根据token解析用户获取当前用户拥有的属性
            const currentUser = await getCurrentUserInfoServe(userId);
            let roleIds = []
            if (currentUser && currentUser.Roles) {
                currentUser.Roles.forEach((role) => {
                    roleIds.push(role.id)
                })
            }
            const currentRole = await getRoleById(roleIds.join(','))
            let routes = [];
            let buttons = [];
            let permissionIds = []
            if (currentRole) {
                if (Array.isArray(currentRole)) {
                    currentRole.forEach(role => {
                        role.Menus.forEach(menu => {
                            permissionIds.push(menu.id)
                        })
                    })
                } else {
                    currentRole.Menus && currentRole.Menus.forEach(menu => {
                        permissionIds.push(menu.id)
                    })
                }

            }
            //由于多个角色有可能permissionId相同,去除重复的Id
            permissionIds = uniqueFunc(permissionIds)

            const allMenu = await getMenuServe()
            const newAllMenu = allMenu.filter(item => {
                if (permissionIds.includes(item.id)) {
                    return {...item}
                }
            })

            newAllMenu.forEach(menu => {
                if (menu.level === 4 && menu.type === 2) {
                    buttons.push(menu.code)
                }
                if (menu.route) {
                    routes.push(menu.route)
                }
            })
            const redisUserInfo = await redis.get(userId)
            let setRedisStatus;
            if (JSON.parse(redisUserInfo)) {
                setRedisStatus = await redis.set(userId, JSON.stringify({
                    ...JSON.parse(redisUserInfo),
                    permissionButtons: buttons
                }))
                redis.expire(userId, 60 * 60 * 12)
                if (setRedisStatus === 'OK') {
                    ctx.body = {
                        data: {
                            routes,
                            buttons,
                            username: currentUser.nickname,
                        },
                        msg: Array.isArray(currentRole) && currentRole.length > 0 || currentRole ? '成功' : '还未配置角色，请联系管理员分配角色',
                        status: 0
                    }
                } else {
                    throw({message: '服务器出现问题'})
                }
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message
            }
        }
    }

    async getUserById(ctx) {
        const {id} = ctx.params;
        try {
            const res = await getUserById(id, false)
            ctx.body = {
                data: res,
                status: 0,
                mag: '获取成功'
            }
        } catch (e) {
            ctx.body = {
                status: 0,
                mag: e.message
            }
        }
    }

    async updateUser(ctx) {
        const {username, nickname} = ctx.request.body
        const {id} = ctx.params;
        try {
            await updateUserServe({username, nickname, id})
            ctx.body = {
                status: 0,
                msg: '修改成功'
            }
        } catch (err) {
            ctx.body = {
                status: 1,
                msg: err.message
            }
        }
    }

    async deleteUser(ctx) {
        const {id} = ctx.params;
        const {user} = ctx.state
        try {
            if (id === user.id) {
                throw ({message: '不能修改自己的状态'})
            }
            if (Number(id) === 2) {
                throw ({message: '管理员不可删除'})
            }
            if (!id) {
                throw ({message: 'id不能为空'})
            }
            const isSuccessDelete = await deleteUserServe(id);
            if (isSuccessDelete) {
                ctx.body = {
                    msg: '删除成功',
                    status: 0,
                    data: isSuccessDelete
                }
            } else {
                throw ({message: '删除失败'})
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async batchDeleteUser(ctx) {
        const {userIds} = ctx.request.body
        try {
            if (userIds) {
                const userIdArr = userIds.split(',')
                for (const userId of userIdArr) {
                    await deleteUserServe(userId)
                }
                ctx.body = {
                    msg: '删除成功',
                    status: 0,
                    data: null
                }
            } else {
                throw ({message: 'id不能为空'})
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async updateUserStatus(ctx) {
        const {id} = ctx.params;
        const {status} = ctx.request.body;
        const {user} = ctx.state;
        try {
            if (id === user.id) {
                throw ({message: '不能修改自己的状态'})
            }
            if (Number(id) === 2) {
                throw ({message: '管理员不可修改'})
            }
            const isSuccessUpdate = await updateUserStatusServe(id, status)
            if (isSuccessUpdate) {
                ctx.body = {
                    msg: '修改成功',
                    status: 0,
                    data: isSuccessUpdate
                }
            } else {
                throw ({message: '修改失败'})
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1,
            }
        }
    }
}

module.exports = new UserController();
